<template>
  <div>
    <CTable
      ref="base"
      :columns="columns"
      :data="data"
      @fetch="fetch"
    >
      <template slot="headerLeft">
        <a-breadcrumb>
          <a-breadcrumb-item><router-link to="/platform/platformmanagement">客户管理</router-link></a-breadcrumb-item>
        </a-breadcrumb>
      </template>
      <a-space>
        <a-button type="primary" @click="changeModel()">
          新增客户
        </a-button>
        <a-button @click="pushPackage">
          套餐管理
        </a-button>
      </a-space>
      <template slot="permission" slot-scope="{record}">
        <a-button type="link" @click="openDetail(record)">{{record.setMealName}}</a-button>
      </template>
      <template slot="combo" slot-scope="{record}">
        {{ record.timeout === null ? "永久" : record.timeout > Date.now() ? moment(record.timeout).format('YYYY-MM-DD') + ' 到期' : '已到期' }}
      </template>
      <template slot="action" slot-scope="{record}">
        <a-button type="link" @click="changeModel(record)">编辑</a-button>
        <a-button type="link" @click="deleteRecord(record)">删除</a-button>
      </template>
    </CTable>
    <a-modal
      v-model="detailShow"
      :title="detail.setMealName"
      :width="480"
      :destroy-on-close="true"
      :footer="null"
    >
      <div class="cmodal">
        <a-form-model layout="inline">
          <a-form-model-item label="套餐权限">
            <a-tree
              :tree-data="treeData"
              :defaultExpandAll="true"
              :replaceFields="{children:'children', title:'name', key:'id' }"
            />
          </a-form-model-item>
          <a-form-model-item label="服务时长">
            <span>{{ detail.detailTime }}</span>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
    <a-modal
      v-model="show"
      :title="recordData.id ? '编辑客户' : '新增客户'"
      :width="480"
      :destroy-on-close="true"
      :confirmLoading="modalLoading"
      @ok="handleOk"
      :afterClose="()=>this.modalLoading = false"
    >
      <div class="cmodal">
        <a-form-model
          ref="editForm"
          :model="form"
          :rules="rules"
          layout="vertical"
        >
          <a-form-model-item
            label="公司名称"
            prop="name"
          >
            <a-input
              v-model="form.name"
              placeholder="请输入用户名"
            />
          </a-form-model-item>
          <a-form-model-item
            label="公司管理员账号"
            prop="account"
          >
            <a-input
              v-model="form.account"
              placeholder="请输入公司管理员账号"
            />
          </a-form-model-item>
          <a-form-model-item
            label="选择套餐"
            prop="setMealId"
          >
            <a-select v-model="form.setMealId">
              <a-select-option :value="item.id" v-for="item in setMealIdList" :key="item.id">
                {{item.name}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <div>服务结束时间: {{setMealTime}}</div>
        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>

<script>
import CTable from '../Template/c-table';
import moment from 'moment';
import {Modal} from 'ant-design-vue';

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'no' }
  },
  {
    title: '公司名称',
    dataIndex: 'name'
  },
  {
    title: '管理员账号',
    dataIndex: 'account'
  },
  {
    title: '权限服务',
    scopedSlots: { customRender: 'permission' }
  },
  {
    title: '套餐状态',
    scopedSlots: { customRender: 'combo' }
  },
  {
    title: '操作',
    scopedSlots: { customRender: 'action' }
  }
];

const data = [];

const treeData = [];

export default {
  name: 'PlatformManagement',
  components: {CTable},
  data() {
    return {
      data,
      columns,
      show: false,
      detailShow: false,
      modalLoading: false,
      recordData: {},
      form: {
        name: '',
        account: '',
        setMealId: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入', trigger: 'blur' }
        ],
        account: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        setMealId: [
          {required: true, message: '请选择', trigger: 'blur', type: 'number'}
        ]
      },
      treeData,
      setMealIdList: [],
      moment,
      detail: {
        detailTime: '',
        setMealName: ''
      }
    };
  },
  created() {
    this.$api.setMeal.listNotPage()
      // eslint-disable-next-line consistent-return
      .then(res => {
        if(res) {
          this.setMealIdList = res;
        }
      })
      .catch(() => {});
  },
  computed: {
    setMealTime() {
      const selectMeal = this.setMealIdList.find(item => item.id === this.form.setMealId);
      const type = {
        '永久': '永久',
        '一个月': moment().add(1, 'M'),
        '三个月': moment().add(3, 'M'),
        '半年': moment().add(6, 'M'),
        '一年': moment().add(1, 'y'),
        '三年': moment().add(3, 'y')
      };
      if(selectMeal && selectMeal.duration) {
        return selectMeal.duration === '永久' ? '永久' : type[selectMeal.duration].format('YYYY-MM-DD');
      }else{
        return '无';
      }
    }
  },
  methods: {
    // eslint-disable-next-line no-shadow
    treeDataPath(treeData, path) {
      treeData.forEach(item => {
        item.path = `${path ? `${path}-` : ''}${item.id}`;
        if(item.children) {
          this.treeDataPath(item.children, item.path);
        }
      });

      return treeData;
    },
    openDetail(record) {
      if(!record.setMealId) {
        this.$message.error('套餐已到期或已删除');
      }else{
        if(record) {
        // eslint-disable-next-line new-cap
          this.$api.customer.SetMealDetailFunctionList({id: record.setMealId}).then(res => {
            if(res) {
              this.treeData = res;
              this.detail.setMealName = record.setMealName;
              if(this.setMealIdList.find(item => item.id === record.setMealId)) {
                this.detail.detailTime = this.setMealIdList.find(item => item.id === record.setMealId).duration;
              }
            }
          });
        }
        this.detailShow = true;
      }
    },
    deleteRecord(record) {
      Modal.confirm({
        title: '删除提示',
        content: `是否删除${record.name}`,
        // eslint-disable-next-line consistent-return
        onOk: () => {
          this.$api.customer.delete({id: record.id})
          // eslint-disable-next-line consistent-return
            .then(res => {
              if(res) {
                return this.$refs.base.fetch();
              }
            })
            .catch(() => {});
        }
      });
    },
    handleOk() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.modalLoading = true;
          this.$api.customer.addAndUpdate({
            ...this.form,
            id: this.recordData.id
          }).then(res => {
            if(res) {
              this.show = false;
              this.$message.info('操作成功');
              this.$refs.base.fetch();
            }
          })
            .catch(() => this.modalLoading = false);
        }
      });
    },
    changeModel(recordData) {
      this.recordData = recordData || {};
      console.log(recordData);
      for(let item in this.form) {
        this.form[item] = recordData ? recordData[item] : '';
      }
      const selectMeal = this.setMealIdList.find(item => item.id === this.form.setMealId);
      if(!selectMeal) {
        this.form.setMealId = '';
      }
      this.show = true;
    },
    pushPackage() {
      this.$router.push('/platform/packagemanagement');
    },
    fetch(params) {
      this.$api.customer.list(params)
        .then(res => {
          if(!res) {
            res = {list: [], total: 0};
          }
          this.data = res.data;
          this.$refs.base.fetchSuccess(res.total);
        })
        .finally(() => {
          this.$refs.base.fetchFinally();
        });
    }
  }
};

</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
/deep/.detailDisplay{
  .ant-tree-checkbox, .ant-tree-checkbox-indeterminate{
    display: none;
  }
  li:not(.ant-tree-treenode-checkbox-checked):not(.ant-tree-treenode-checkbox-indeterminate){
    display: none;
  }
}
.cmodal{
  padding: 0 76px;
}
</style>
